<template>
  <div class="article_all">
    <el-page-header
      @back="goBack"
      content="网站设置"
      style="margin-bottom: 20px"
    ></el-page-header>

    <!-- 网站信息区域 -->
    <div class="site-info">
      <div class="site-logo">
        <el-upload
          :disabled="siteData.sitePic !== null && siteData.sitePic !== ''"
          :file-list="sitePicList"
          :multiple="false"
          drag
          ref="uploadCover"
          action="#"
          list-type="picture"
          :auto-upload="false"
          class="upload"
          accept="image/*"
          :on-change="handleChange"
          :on-remove="handleRemove"
        >
          <div
            v-if="siteData.sitePic === ''"
            style="display: flex; flex-direction: column; align-items: center"
          >
            <img
              :src="require('@/assets/article/uploadimage.png')"
              alt="Upload Image"
              class="upload_image"
            />
            <div class="el-upload__text upload_tip">
              拖拽图片到此区域也可上传<span>
                <em>上传</em>一张不超过 2MB 的image/*文件
              </span>
            </div>
          </div>
          <div v-else class="url_image">
            <el-image
              :preview-src-list="[siteData.sitePic.url || siteData.sitePic]"
              :src="siteData.sitePic.url || siteData.sitePic"
              class="url_img"
              ref="urlPic"
            ></el-image>
            <div class="url_drow">
              <i class="el-icon-delete" @click.stop="removeImage"></i>
              <i
                class="el-icon-zoom-in"
                @click="handlePreview($refs.urlPic)"
              ></i>
            </div>
          </div>
        </el-upload>
      </div>

      <div class="site-details">
        <div class="info-item">
          <span class="info-label">网站名称:</span>
          <el-input
            v-model="siteData.siteName"
            placeholder="请输入网站名称"
          ></el-input>
        </div>
        <div class="info-item">
          <span class="info-label">网址:</span>
          <el-input
            v-model="siteData.siteUrl"
            placeholder="请输入网址"
          ></el-input>
        </div>
        <div class="info-item">
          <span class="info-label">是否上线:</span>
          <el-radio-group v-model.trim="siteData.onlineState">
            <el-radio label="0">未上线</el-radio>
            <el-radio label="1">上线</el-radio>
          </el-radio-group>
        </div>
        <div class="info-item upload-favicon">
          <span class="info-label">浏览器图标:</span>
          <el-upload
            action=""
            list-type="picture"
            :auto-upload="false"
            :on-change="handleIconChange"
            :limit="1"
            :file-list="fileList"
          >
            <el-button>添加图片</el-button>
          </el-upload>
          <span class="icon-suggestion">建议尺寸：16X16PX</span>
        </div>
      </div>
    </div>

    <!-- 设置区域 -->
    <div class="settings-area">
      <div v-for="(item, index) in settings" :key="index" class="setting-box">
        <div class="preview-box">{{ item }}</div>
        <el-button type="text" class="set-button">设置</el-button>
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <!-- 加载状态 -->
    <div class="loading" v-load:[loadText]="loading" />
  </div>
</template>

<script>
import {
  postSiteList,
  getFolderId,
  fileUpload,
  updateOnlineStatus,
  editSiteInfo,
} from "@/api/api";
export default {
  name: "WebsiteSettings",
  data() {
    return {
      siteData: {
        createAt: "2024-07-11 16:06:41",
        createBy: "ff80808186e9567c01877d725b5d0278",
        createName: "肖业丽",
        delFlag: 0,
        id: "40287e0190a0cfe40190a0d4883f0002",
        onlineState: "1",
        siteLogo:
          "http://home.i3vsoft.com:1080/group1/中国民企/官网/30fdc5596f555d3eab7cb9a3612efcaa.png",
        siteName: "",
        sitePic:
          "http://home.i3vsoft.com:1080/group1/中国民企/官网/30fdc5596f555d3eab7cb9a3612efcaa.png",
        siteUrl: "dist/template/艾三维技术/index.html",
        updateAt: null,
        updateBy: "ff80808186e9567c01877d725b5d0278",
        updateName: null,
      }, // 站点信息
      settings: [
        "悬浮客服",
        "悬浮二维码",
        "网站侧栏",
        "顶部广告",
        "底部广告",
        "VIP",
      ], // 设置的项目
      sitePicList: [], // 站点图片列表
      fileList: [],
      dialogVisible: false,
      loadText: "加载中···",
      loading: false,
      dialogImageUrl: "",
      isInitialized: false, // 防止初始化时触发watch
    };
  },
  async created() {
    // 获取站点默认页面
    const res = await postSiteList(this.$route.query.id);
    if (res.data.result) {
      if (res.data.result.onlineState) {
        res.data.result.onlineState = res.data.result.onlineState.toString();
      }
      this.siteData = res.data.result;
      this.fileList = [
        {
          name: "浏览器图标",
          url: this.siteData.siteLogo,
        },
      ];
      this.isInitialized = true;
    }
  },
  watch: {
    siteData: {
      handler(newVal, oldVal) {
        if (this.isInitialized) {
          console.log(newVal, oldVal);
          this.editSiteData(newVal, oldVal);
        }
      },
      immediate: false,
      deep: true,
    },
  },
  methods: {
    handlePreview() {
      // 预览图片逻辑
      this.dialogImageUrl = this.siteData.sitePic;
      this.dialogVisible = true;
    },
    handleRemove() {
      // 删除图片逻辑
      this.siteData.sitePic = "";
    },
    //图片的上传
    handleChange(file, fileList) {
      this.$refs.uploadCover.clearFiles();
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
        return;
      }
      let isAccept = new RegExp("image/*").test(file.raw.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
        return;
      }
      this.siteData.sitePic = file;
      this.sitePicList[0] = file;
    },
    removeImage() {
      this.siteData.sitePic = ""; // 移除图片
    },

    handleIconChange(file) {},
    // 上传文件
    async uploadFile(file) {
      const filderId = await this.getFolderId();
      const formData = new FormData();
      formData.append("file", file);
      formData.append("folderId", filderId);
      formData.append("isCover", "0");
      // 下面返回上传路径
      return await fileUpload(formData)
        .then((resp) => {
          if (resp.data.code == 200) {
            return resp.data.result.src;
          } else {
            throw new Error("上传失败");
          }
        })
        .catch((e) => {
          throw new Error("处理失败");
        });
    },
    // 获取文件夹id
    async getFolderId() {
      return getFolderId({
        folderName: "官网",
        folderDescribe: "官网目录自动创建",
        folderAttributes: '{"dataType":0}',
      })
        .then((resp) => {
          if (resp.data.code == 200) {
            return resp.data.result;
          } else {
            this.$message.error("文件夹路径获取失败！");
          }
        })
        .catch((e) => {
          this.$message.error("处理失败！");
        });
    },

    // 编辑表单
    async editSiteData(newVal, oldVal) {
      // 当上线状态改变时，更新上线状态
      if (newVal.onlineState !== oldVal.onlineState) {
        const res = await updateOnlineStatus({
          id: oldVal.id,
          onlineState: Number(this.siteData.onlineState),
        });
        if (res.data.code === 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      } else if (
        newVal.siteName !== oldVal.siteName ||
        newVal.siteUrl !== oldVal.siteUrl ||
        newVal.sitePic !== oldVal.sitePic
      ) {
        const res = await editSiteInfo({
          id: this.siteData.id,
          siteName: this.siteData.siteName,
          siteUrl: this.siteData.siteUrl,
          sitePic: this.siteData.sitePic,
        });
        if (res.data.code === 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      }
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
.article_all {
  margin: 20px;
}

/* 网站信息区域布局优化 */
.site-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.site-logo {
  width: 150px;
  text-align: center;
}

.upload >>> .el-upload-dragger {
  width: 148px;
  height: 148px;
  opacity: 1;
  border-radius: 10px;
  background: rgba(253, 252, 255, 1);
  border: 1px dashed rgba(126, 114, 242, 1);
  /* z-index: 1; */
}

.upload >>> .el-upload--picture-card {
  width: auto;
  border-radius: 10px;
  height: auto;
}

.upload {
  position: relative;
  height: 170px;
  /* z-index: 1; */
}

.upload_image {
  width: 50px;
  height: 50px;
  margin-top: 30px;
}

.upload_content {
  display: flex;
  flex-direction: column;
}

.upload_tip {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.url_drow {
  display: none;
  color: white;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: default;
  position: absolute;
  background-color: rgba(118, 116, 116, 0.589);
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

.url_drow i {
  cursor: pointer;
  margin-left: 5px;
  margin-right: 5px;
}

.url_drow i:hover {
  color: rgb(126, 114, 242);
}

.url_image:hover .url_drow {
  display: flex;
}

.url_img {
  width: 148px;
  height: 148px;
  animation-duration: 0.5s;
  animation-fill-mode: both;
  animation-name: fadeInDown;
  backface-visibility: visible !important;
}
@keyframes fadeInDown {
  from {
    transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
    animation-timing-function: ease-in;
    opacity: 0;
  }

  40% {
    transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
    animation-timing-function: ease-in;
  }

  60% {
    transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
    opacity: 1;
  }

  80% {
    transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
  }

  to {
    transform: perspective(400px);
  }
}
@keyframes flipOutX {
  from {
    transform: perspective(400px);
  }

  30% {
    transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
    opacity: 1;
  }

  to {
    transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
    opacity: 0;
  }
}

.flipOutX {
  animation-duration: calc(0.8s * 0.75);
  animation-name: flipOutX;
  backface-visibility: visible !important;
}

.uploaded-logo {
  width: 148px;
  height: 148px;
  object-fit: cover;
}

/* 调整上传按钮的样式 */
.el-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.change-btn {
  /* position: absolute;
  top:70px;
  left: 150px; */
  margin-top: 10px;
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
}

.site-details {
  width: 100%;
  padding-left: 20px;
}

.info-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.info-label {
  width: 100px;
  text-align: right;
  margin-right: 10px;
  font-weight: 500;
}

.upload-favicon {
  display: flex;
  align-items: flex-start;
}

.icon-suggestion {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}

/* 设置区域布局优化 */
.settings-area {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-gap: 20px;
}

.setting-box {
  width: 148px;
  height: 148px;
  border: 1px solid #dcdcdc;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f4f4f4;
  position: relative;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.preview-box {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.set-button {
  position: absolute;
  bottom: 10px;
  font-size: 12px;
  color: #409eff;
}

@media screen and (max-width: 768px) {
  .settings-area {
    flex-direction: column;
    align-items: center;
  }

  .site-info {
    flex-direction: column;
    align-items: center;
  }

  .site-details {
    padding-left: 0;
    text-align: left;
  }

  .info-label {
    text-align: left;
    width: auto;
  }
}
</style>
